package com.bby.screentool.service.impl;

import com.bby.screentool.bean.Action;
import com.bby.screentool.config.Context;
import com.bby.screentool.controller.MWebSocket;
import com.bby.screentool.service.ScreenService;
import com.bby.screentool.utils.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import static com.bby.screentool.config.Context.idCache;
import static com.bby.screentool.config.Context.sessionIdCache;

@Slf4j
@Service
public class ScreenServiceImpl implements ScreenService {

    @Override
    public String getScreenId() {
        String sessionId = RequestUtil.getSessionId();
        if (sessionIdCache.containsKey(sessionId)) {
            return sessionIdCache.get(sessionId);
        }
        if (sessionIdCache.size() > 100) {
            return "";
        }
        String id = createScreenId();
        sessionIdCache.put(sessionId, id);
        idCache.put(id, sessionId);
        log.debug(sessionId);
        return id;
    }


    @Override
    public Action checkScreenId(String screenId) {
        MWebSocket socket = Context.getSocketServer(screenId);
        if (socket != null && socket.isRecord()) {
            return new Action(Action.SUCCESS);
        }
        return new Action(Action.NOT_RECORD, "", screenId);
    }

    private String createScreenId() {
        String id = String.valueOf((int) ((Math.random() + 0.1) * 100));
        if (idCache.containsKey(id)) {
            id = createScreenId();
        }
        return id;
    }
}
